﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using BusinessLogic.BusinessEntity.Entities;
using UserInterface.ClientApplication.UIEntity;


namespace UserInterface.ClientApplication
{
	public partial class InvoiceForm : Form, IForm
	{
		private RemittanceAdviceView RA = new RemittanceAdviceView();

		private int ind = -1;

		public InvoiceForm()
		{
			InitializeComponent();
		}



		public static void ValidateDigitText(object sender, EventArgs e)
		{

			TextBox t = (TextBox)sender;
			string s = t.Text;
			for (int i = s.Length - 1; i >= 0; i--)
			{
				if (!Char.IsDigit(s[i]) && !(s[i] == ',' && !s.Remove(i, 1).Contains(',') && i != 0))
					s = s.Remove(i--, 1);
			}
			t.Text = s;
			t.SelectionStart = s.Length;

		}








		#region IForm Members

		public FormManager fm { get; set; }




		public DialogResult Show(FormManager fm)
		{
			this.fm = fm;
			/*int ind = (int)fm.Param;
			if (ind >= 0)
			{
				RA = fm.GetRA(ind);
			}*/
			return ShowDialog();
		}

		#endregion

		private void AmountTextBox_TextChanged(object sender, EventArgs e)
		{
			ValidateDigitText(sender, e);
		}

		private void InvoiceForm_Load(object sender, EventArgs e)
		{
			if (fm.Param is Array)
			{
				int[] arr = (int[])fm.Param;
				BackToDraftButton.Visible = false;
				ValidateButton.Visible = false;
				SaveButton.Visible = false;
				RejectionDetailTextBox.Visible = true;
				RejectionDetailTextBox.Text = fm.GetSendedRA()[arr[0]].RejectionReason;
				RA = fm.GetSendedRA()[arr[0]];
				ind = 1;
				MainGroupBox.Enabled = false;
				InitBinding();
				CurrencyComboBox.SelectedIndex = GetCurrencyInd(RA.Currency);
				RecepientIBANComboBox.SelectedItem = RA.BillToPartyAccount;
				//CurrencyComboBox.SelectedItem = ind == -1 ? null : RA.Currency;
				RecepientNameComboBox.SelectedItem =  RA.BillToPartyAccount.Accountee;
				PayerIBANComboBox.SelectedIndex = GetIbanInd(RA.PayerPartyAccount);
				return;
			}
			try
			{
				
				ind = (int)fm.Param;
				if (ind != -1)
				{
					RA = fm.GetRA(ind);
					
				}
				
			}
			catch (Exception)
			{
			}
			finally
			{
				
				InitBinding();
				try
				{
					if (RA.Status == null || 
						(RemittanceAdviceStatus)Enum.Parse(typeof(RemittanceAdviceStatus), RA.GetOriginalStatus())
						!= RemittanceAdviceStatus.ReadyToSign)
					{
						BackToDraftButton.Enabled = false;
						MainGroupBox.Enabled = true;
						ValidateButton.Enabled = true;
					}
					else
					{
						BackToDraftButton.Enabled = true;
						MainGroupBox.Enabled = false;
						ValidateButton.Enabled = false;
					}
					
					//PayerIBANComboBox.SelectedItem = ind == -1 ? null : RA.PayerPartyAccount.Number;
					CurrencyComboBox.SelectedIndex = GetCurrencyInd(RA.Currency);
					RecepientIBANComboBox.SelectedItem = ind == -1 ? null : RA.BillToPartyAccount;
					//CurrencyComboBox.SelectedItem = ind == -1 ? null : RA.Currency;
					RecepientNameComboBox.SelectedItem = ind == -1 ? null : RA.BillToPartyAccount.Accountee;
					PayerIBANComboBox.SelectedIndex = GetIbanInd(RA.PayerPartyAccount);
				}
				catch(Exception)
				{
					if(RA.BillToPartyAccount == null)
					{
						RecepientIBANComboBox.SelectedItem = null;
						RecepientNameComboBox.SelectedItem = null;
					}
				}
				if (ind == -1)
				{
					PayerIBANComboBox.SelectedItem = null;
					RecepientNameComboBox.SelectedItem = null;
					RecepientIBANComboBox.SelectedItem = null;
				}

			}
		}

		private int GetIbanInd(AccountView accountView)
		{
			if (accountView == null)
			{
				return -1;
			}
			for (int i = 0; i < fm.GetMyAccounts().Count; i++)
			{
				if (accountView.Number == fm.GetMyAccounts()[i].Number)
				{
					return i;
				}
			}
			return -1;
		}

		private int GetCurrencyInd(CurrencyView curr)
		{
			if(curr == null)
			{
				return -1;
			}
			for(int i = 0; i < fm.GetAllCurrency().Count; i++)
			{
				if(curr.Name == fm.GetAllCurrency()[i].Name)
				{
					return i;
				}
			}
			return -1;
		}

		private void InitBinding()
		{
			InvoiceNumberTextBox.DataBindings.Add("Text", RA, "Number");
			
			new ExceptionCatcher().Execute(()=>
			                               {
											  
											   AmountTextBox.DataBindings.Add("Text", RA, "TotalAmount");
											  
											   DescriptionRichTextBox.DataBindings.Add("Text", RA, "Description");
											   RecepientNameComboBox.DataSource = fm.GetCopyClient();
											   RecepientNameComboBox.DisplayMember = "Name";
											   RecepientNameComboBox.ValueMember = "Name";
											   
											   RecepientIBANComboBox.DataSource = fm.GetCopyAccount();
											   RecepientIBANComboBox.DisplayMember = "Number";
											   RecepientIBANComboBox.ValueMember = "Number";
											   CurrencyComboBox.DataSource = fm.GetAllCurrency();
											   CurrencyComboBox.DisplayMember = "Name";
											   CurrencyComboBox.ValueMember = "Name";
											   PayerIBANComboBox.DataSource = fm.GetMyAccounts();
											   PayerIBANComboBox.DisplayMember = "Number";
											   PayerIBANComboBox.ValueMember = "Number";

			                               });
			
		}

		private void CancelButton_Click(object sender, EventArgs e)
		{
			//fm.LoadState();
			Close();
		}

		private void SaveButton_Click(object sender, EventArgs e)
		{
			
			/*
			if (RecepientIBANComboBox.SelectedItem == null || PayerIBANComboBox.SelectedItem == null)
			{
				MessageBox.Show("Пожалуйста, выберите счет", "Сохранение", MessageBoxButtons.OK,
								MessageBoxIcon.Information);
				return;
			}*/
			if(fm.Param is Array)
			{
				Close();
			}
			if (ind == -1)
			{
				if (RecepientIBANComboBox.SelectedItem != null)
				{
					RA.BillToPartyAccount = (AccountView)RecepientIBANComboBox.SelectedItem;
					
				}
				if(PayerIBANComboBox.SelectedItem != null)
				{
					RA.PayerPartyAccount = (AccountView)PayerIBANComboBox.SelectedItem;
				}
				//RA.PayerPartyAccount = new AccountView();
				//SelectNextControl(SaveButton, false, false, false, false);
				RA.Currency = (CurrencyView)CurrencyComboBox.SelectedItem;
				if (string.IsNullOrEmpty(RA.Status))
				{
					RA.Status = RemittanceAdviceStatus.Pending.ToString();
				}
				fm.AddRA(RA);
			}
			else
			{
				RA.BillToPartyAccount = (AccountView)RecepientIBANComboBox.SelectedItem;
				RA.PayerPartyAccount = (AccountView)PayerIBANComboBox.SelectedItem;
				RA.Currency = (CurrencyView)CurrencyComboBox.SelectedItem;
				
				if (string.IsNullOrEmpty(RA.Status))
				{
					RA.Status = RemittanceAdviceStatus.Pending.ToString();
				}
				fm.SaveState();
			}
			Close();
		}


		

		private void RecepientNameComboBox_SelectedIndexChanged(object sender, EventArgs e)
		{
			if (RecepientNameComboBox.SelectedItem != null)
			{
				IList<AccountView> bindingList = fm.GetAllAccount().Where(
						x => x.Accountee == (ClientView)RecepientNameComboBox.SelectedItem).ToList();
				if (bindingList.Count > 0)
				{
					RecepientIBANComboBox.DataSource = bindingList;
						
				}else
				{
					RecepientIBANComboBox.DataSource = null;
					RecepientIBANComboBox.DisplayMember = null;
					RecepientIBANComboBox.SelectedIndex = -1;
				}
			}
			else
			{
				RecepientIBANComboBox.DataSource = null;
				RecepientIBANComboBox.SelectedIndex = -1;

			}
		}

		private void ValidateButton_Click(object sender, EventArgs e)
		{
			if(ValidateChildren())
			{
				MessageBox.Show("Платежное поручение заполнено верно", "Проверка заполнения", MessageBoxButtons.OK,
				                MessageBoxIcon.Information);
				;
				RA.Status = RemittanceAdviceStatus.ReadyToSign.ToString();
				MainGroupBox.Enabled = false;
				ValidateButton.Enabled = false;
				BackToDraftButton.Enabled = true;
			}else
			{
				DialogResult = System.Windows.Forms.DialogResult.None;
			}
		}

		private void BackToDraftButton_Click(object sender, EventArgs e)
		{
			RA.Status = RemittanceAdviceStatus.Pending.ToString();
			BackToDraftButton.Enabled = false;
			ValidateButton.Enabled = true;
			MainGroupBox.Enabled = true;
		}

		private void InvoiceForm_FormClosing(object sender, FormClosingEventArgs e)
		{
			try
			{
				if(DialogResult == System.Windows.Forms.DialogResult.OK)
				{
					e.Cancel = true;
					return;
				}
				if(DialogResult != System.Windows.Forms.DialogResult.Yes)
				{
					fm.LoadState();
				}
			}catch(Exception ex){}
		}

		private void PayerIBANComboBox_Validating(object sender, CancelEventArgs e)
		{
			string error = null;
			if(PayerIBANComboBox.SelectedItem == null)
			{
				error = "Выберите расчетный счет";
				e.Cancel = true;
			}
			ErrorProvider.SetError((Control)sender, error);
		}

		private void RecepientNameComboBox_Validating(object sender, CancelEventArgs e)
		{
			string error = null;
			if (RecepientNameComboBox.SelectedItem == null)
			{
				error = "Выберите контрагента";
				e.Cancel = true;
			}
			ErrorProvider.SetError((Control)sender, error);
		}

		private void CurrencyComboBox_Validating(object sender, CancelEventArgs e)
		{
			string error = null;
			if (CurrencyComboBox.SelectedItem == null)
			{
				error = "Выберите валюту";
				e.Cancel = true;
			}
			ErrorProvider.SetError((Control)sender, error);
		}

		private void AmountTextBox_Validating(object sender, CancelEventArgs e)
		{
			string error = null;
			try
			{
				decimal amount = Decimal.Parse(AmountTextBox.Text);
				if(amount <= 0)
				{
					error = "Сумма должна быть положительной";
					e.Cancel = true;
				}
			}catch(Exception ex)
			{
				error = "Здесь должна быть цифра";
				e.Cancel = true;
			}
			ErrorProvider.SetError((Control)sender, error);
		}

		private void InvoiceNumberTextBox_Validating(object sender, CancelEventArgs e)
		{
			string error = null;
			string number = InvoiceNumberTextBox.Text;
			if(number.Length < 8)
			{
				error = "Длина номера должна быть больше 8 знаков";
				e.Cancel = true;
			}
			if (number.Length > 16)
			{
				error = "Длина номера должна быть не больше 16 знаков";
				e.Cancel = true;
			}
			Regex regexp = new Regex("[^0-9]");
			if (regexp.IsMatch(number))
			{

				if(error != null)
				{
					error += "\nДопускаются только цифры";
				}
				else
				{
					error = "Допускаются только цифры6";
				}
				e.Cancel = true;

			}
			if(fm.IsExistRA(RA))
			{
				if (error != null)
				{
					error += "\nТакой номер платежного поручение уже существует";
				}
				else
				{
					error = "Такой номер платежного поручение уже существует";
				}
				e.Cancel = true;
			}
			ErrorProvider.SetError((Control)sender, error);
		}

		private void DescriptionRichTextBox_Validating(object sender, CancelEventArgs e)
		{
			string error = null;
			if(DescriptionRichTextBox.Text.Length == 0)
			{
				error = "Введите назначение платежа";
				e.Cancel = true;
			}
			ErrorProvider.SetError((Control)sender, error);
		}

		private void RecepientIBANComboBox_Validating(object sender, CancelEventArgs e)
		{
			string error = null;
			if (RecepientIBANComboBox.SelectedIndex == -1)
			{
				error = "Выберите счет";
				e.Cancel = true;
			}
			ErrorProvider.SetError((Control)sender, error);
		}
		
	}
}
